package fpt.edu.vn.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hsqldb.lib.StringUtil;

import fpt.edu.vn.model.Favorites;
import fpt.edu.vn.model.Roles;
import fpt.edu.vn.model.Topics;
import fpt.edu.vn.model.Users;
import fpt.edu.vn.util.HibernateUtil;

/* 
 * TopicsDao.java
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class UsersDao {

	public Users add(Users user) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		return user;
	}

	public Favorites addFavorites(Favorites favorites) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(favorites);
		session.getTransaction().commit();
		return favorites;
	}

	@SuppressWarnings("unchecked")
	public boolean emailSearch(String email) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> emailCheck = null;
		try {
			emailCheck = (List<Object>) session.createQuery(
					"select u.email from Users u where u.email =  '" + email
							+ "'").list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		if (emailCheck.size() < 1)
			return true;
		else
			return false;

	}

	@SuppressWarnings("unchecked")
	public List<Object> list(String email) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> users = null;
		try {

			users = (List<Object>) session
					.createQuery(
							"select u.usersId, u.displayName, u.createDate , u.lastLoginDate, u.avatar from Users u where u.email like '"
									+ email + "'").list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return users;
	}

	@SuppressWarnings("unchecked")
	public List<Object> listuser() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> users = null;
		try {

			users = (List<Object>) session
					.createQuery(
							"select u.usersId, u.displayName, u.email , u.createDate , u.lastLoginDate, r.roleName,u.roleId,u.isBanner from Users u, Roles r where u.roleId = r.roleId ")
					.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return users;
	}

	// -------------
	@SuppressWarnings("unchecked")
	public List<Object> searchUser(String search_email, String fromregdate,
			String toregdate, String search_name, String fromentdate,
			String toentdate, int search_banned, int search_reglevel,
			String search_order_r, String search_order_l) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> user = null;
		try {
			StringBuffer hsql = new StringBuffer();
			hsql.append("select u.usersId, u.displayName, u.email , u.createDate , u.lastLoginDate, r.roleName,u.roleId,u.isBanner from Users u, Roles r ");
			hsql.append("WHERE u.roleId = r.roleId ");
			if (!StringUtil.isEmpty(search_email))
				hsql.append("AND LOWER(u.email) LIKE :email ");
			if (!StringUtil.isEmpty(fromregdate))
				hsql.append("AND DATE_FORMAT( u.createDate, '%Y-%m-%d') >= :fromregdate ");
			if (!StringUtil.isEmpty(toregdate))
				hsql.append("AND DATE_FORMAT( u.createDate, '%Y-%m-%d') <= :toregdate ");
			if (!StringUtil.isEmpty(search_name))
				hsql.append("AND LOWER(u.displayName) LIKE :displayName ");
			if (!StringUtil.isEmpty(fromentdate))
				hsql.append("AND DATE_FORMAT( u.lastLoginDate, '%Y-%m-%d') >= :fromentdate ");
			if (!StringUtil.isEmpty(toentdate))
				hsql.append("AND DATE_FORMAT( u.lastLoginDate, '%Y-%m-%d') <= :toentdate ");
			if (search_banned==1)
				hsql.append("AND LOWER(u.isBanner) = :isBanner ");
			if (search_reglevel!=0)
				hsql.append("AND LOWER(u.roleId) = :roleId ");
			String order="";
			if ("desc".equals(search_order_r))
				order="order by u.createDate desc";
			if ("asc".equals(search_order_r))
				order="order by u.createDate asc";
			if ("desc".equals(search_order_l))
				order="order by u.lastLoginDate desc";
			if ("asc".equals(search_order_l))
				order="order by u.lastLoginDate asc";
			hsql.append(order);

			Query query = session.createQuery(hsql.toString());
			if (!StringUtil.isEmpty(search_email))
				query.setParameter("email", "%" + search_email + "%");
			if (!StringUtil.isEmpty(fromregdate))
				query.setParameter("fromregdate",  fromregdate );
			if (!StringUtil.isEmpty(toregdate))
				query.setParameter("toregdate", toregdate);
			if (!StringUtil.isEmpty(search_name))
				query.setParameter("displayName", "%" + search_name + "%");
			if (!StringUtil.isEmpty(fromentdate))
				query.setParameter("fromentdate", fromentdate);
			if (!StringUtil.isEmpty(toentdate))
				query.setParameter("toentdate", toentdate);
			if (search_banned==1)
				query.setParameter("isBanner", search_banned);
			if (search_reglevel!=0)
				query.setParameter("roleId", search_reglevel);
			
			user = query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return user;
	}

	// ------------
	@SuppressWarnings("unchecked")
	public List<Roles> listRoles() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Roles> users = null;
		try {

			users = (List<Roles>) session.createQuery("from Roles r").list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return users;
	}
	//get name delete
	@SuppressWarnings("unchecked")
	public List<Users> listdeleteuser(int usersId) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Users> users = null;
		try {
			StringBuffer hsql = new StringBuffer();
			hsql.append("from Users u ");
			hsql.append("where usersId= :usersId");
			Query query = session.createQuery(hsql.toString());
			query.setParameter("usersId", usersId);
			users = query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return users;
	}
	@SuppressWarnings("unchecked")
	public List<Object> listProfile(int userId) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Object> users = null;
		try {

			users = (List<Object>) session
					.createQuery(
							"select u.usersId, u.displayName, u.createDate , u.lastLoginDate, u.avatar, u.email,u.roleId,u.isBanner from Users u where u.usersId = "
									+ userId).list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return users;
	}

	@SuppressWarnings("unchecked")
	public List<Topics> countNumberPost(int userId) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Topics> topic = null;
		try {

			topic = (List<Topics>) session
					.createQuery(
							"select COUNT(t.topicId) from Topics t, Users u where u.usersId = t.usersId and u.usersId ="
									+ userId).list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return topic;
	}

	@SuppressWarnings("unchecked")
	public List<Topics> listOwnerTopic(int userId) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Topics> topics = null;
		try {

			topics = (List<Topics>) session
					.createQuery(
							"select t.title, t.address, t.price, t.area, t.viewNum, t.createDate, t.latitude, t.longitude, t.image, t.topicId, t.description, t.topicTypeId , t.districtId, u.displayName, d.districtName, t.statusTopicId from Topics t, Districts d, Users u where t.districtId = d.districtId and t.usersId = u.usersId and  u.usersId = "
									+ userId + " order by t.renewDate desc")
					.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return topics;
	}

	@SuppressWarnings("unchecked")
	public List<Topics> listOwnerFavorite(int userId) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Topics> topics = null;
		try {

			topics = (List<Topics>) session
					.createQuery(
							"select t.title, t.address, t.price, t.area, t.viewNum, t.createDate, t.latitude, t.longitude, t.image, t.topicId, t.description, t.topicTypeId , t.districtId, u.displayName, d.districtName, t.statusTopicId from Topics t, Districts d, Users u, Favorites f where t.districtId = d.districtId and t.topicId = f.topicId and t.usersId = u.usersId and t.usersId = u.usersId and  f.usersId = "
									+ userId + " order by t.renewDate desc")
					.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return topics;
	}

	// [delete] =update default avatar
	public boolean deleteAvatar(int usersId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean update = false;
		try {
			String hql = "update Users set avatar = 'anonymous.png' where usersId ="
					+ usersId;
			Query query = session.createQuery(hql);
			int rowCount = query.executeUpdate();
			if (rowCount < 1) {
			} else {
				update = true;
			}

		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return update;
	}
	//// update topic
	public boolean AdminUpdateUser(Users user) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Users usertemp = (Users) session.load(Users.class, user.getUsersId());
		if(user.getDisplayName()!=null && !"".equals(user.getDisplayName()))
		usertemp.setDisplayName(user.getDisplayName());
		if(user.getAvatar()!=null)
		usertemp.setAvatar(user.getAvatar());
		usertemp.setIsBanner(user.getIsBanner());
		if(user.getRoleId()!=0)
		usertemp.setRoleId(user.getRoleId());
		session.update(usertemp);
		session.getTransaction().commit();
		return true;
	}
	// [update display name and avatar] =update default avatar
	public boolean UpdateProfile(int usersId, String displayName, String src) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean update = false;
		try {
			String hql = "update Users set avatar = '" + src
					+ "' , displayName = '" + displayName + "' where usersId ="
					+ usersId;
			Query query = session.createQuery(hql);
			int rowCount = query.executeUpdate();
			if (rowCount < 1) {
			} else {
				update = true;
			}

		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return update;
	}

	// [update display name] =update default avatar
	public boolean UpdateProfile(int usersId, String displayName) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean update = false;
		try {
			String hql = "update Users set displayName = '" + displayName
					+ "' where usersId =" + usersId;
			Query query = session.createQuery(hql);
			int rowCount = query.executeUpdate();
			if (rowCount < 1) {
			} else {
				update = true;
			}

		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return update;
	}

	// [update lastLogindate ]
	public boolean updateLastLogin(int usersId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean update = false;
		try {
			String hql = "update Users set lastLoginDate = NOW() where usersId ="
					+ usersId;
			Query query = session.createQuery(hql);
			int rowCount = query.executeUpdate();
			if (rowCount < 1) {
			} else {
				update = true;
			}

		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return update;
	}
	public boolean deletedUser(int usersId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		boolean delete = false;
		try {
			String hql = "delete from Users where usersId =" + usersId;
			Query query = session.createQuery(hql);
			int rowCount = query.executeUpdate();
			if (rowCount < 1) {
			} else {
				delete = true;
			}

		} catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		session.getTransaction().commit();
		return delete;
	}
	//update password
	public boolean updatePassWord(int userid,String password) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Users usertemp = (Users) session.load(Users.class, userid);
		usertemp.setPassword(password);
		session.update(usertemp);
		session.getTransaction().commit();
		return true;
	}
	
}
